package test1.authenticator;


import java.util.Collection;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.pam.AbstractAuthenticationStrategy;
import org.apache.shiro.realm.Realm;

public class OnlyOneAuthenticatorStrategy extends AbstractAuthenticationStrategy{

	public AuthenticationInfo beforeAllAttempts(Collection<? extends Realm> realms,AuthenticationToken token)throws AuthenticationException{
		
		return new SimpleAuthenticationInfo();
	}
	
	public AuthenticationInfo beforeAttempt(Realm realm,AuthenticationToken token,AuthenticationInfo aggregate)throws AuthenticationException{
		
		return aggregate;
	}
	
	public AuthenticationInfo afterAttempt(Realm realm,AuthenticationToken token,AuthenticationInfo singleRealmInfo,AuthenticationInfo aggregate,Throwable t){
		AuthenticationInfo info;
		if(null==singleRealmInfo){
			info= aggregate;
		}else{
			info= merge(singleRealmInfo,aggregate);
			
			if(info.getPrincipals().getRealmNames().size()>1){
				System.out.println(info.getPrincipals().getRealmNames());
				 throw new AuthenticationException("Authentication token of type [" + token.getClass() + "] " +
                         "could not be authenticated by any configured realms.  Please ensure that only one realm can " +
                         "authenticate these tokens.");
			}
		}
		return info;
	}
	
	public AuthenticationInfo afterAllAttempts(AuthenticationToken token,AuthenticationInfo aggregate)throws AuthenticationException{
		
		return aggregate;
	}
}
